#!/usr/bin/python

import argparse, synchronize, time, exceptions, logging, filesys, cache, os.path, ui
logging.basicConfig(level=logging.DEBUG)




class Sachem:
	
	def __init__(self):
		self._localDir='.'
		self._sacvoyageUrl='' 
		self._interval=60
		self._env={}
		
	def setSacvoyageUrl(self, url):
		self._sacvoyageUrl=url

	def setLocalUrl(self, dirName):
		self._localDir=dirName
		
	def setInteval(self, interval):
		self._interval=interval
		
	def run(self):
		if not self._env.get('cache'):
			self._env['cache']=cache.MemoryCache()
			try:    
				self._env['cache'].unserialize(open(os.path.expanduser('~/.sachem/cache.json')).read())
			except:	
				pass
		if not self._env.get('ui'):
			self._env['ui']=ui.CLI()
		
		
		
		self._localFs=filesys.LocalFS(self._localDir)
		self._sacvoyageFs=filesys.SacvoyageFS(self._sacvoyageUrl)
		self._synchronizer=synchronize.Synchronizer(self._localFs, self._sacvoyageFs, self._env)
		while True:
			self._synchronizer.synchronize()
			time.sleep(self._interval)
	def finalize(self):
		if self._env.get('cache'):
			try: os.makedirs(os.path.expanduser('~/.sachem'))
			except: pass
			open(os.path.expanduser('~/.sachem/cache.json'), 'w')\
			.write(self._env['cache'].serialize())




parser=argparse.ArgumentParser()
parser.add_argument('--sacvoyage',  '-s', required=True)
parser.add_argument('--directory',  '-d', default='.', required=True)
arguments=parser.parse_args()


sach=Sachem()
sach.setInteval(5)
sach.setSacvoyageUrl(arguments.sacvoyage)
sach.setLocalUrl(arguments.directory)
try:
	sach.run()
except exceptions.SystemExit as e:
	print 'exit sachem'
finally:
	# save cache
	sach.finalize()


